package com.bookstore.controller;

import com.bookstore.dto.OrderDTO;
import com.bookstore.entity.Order;
import com.bookstore.entity.User;
import com.bookstore.service.CartService;
import com.bookstore.service.OrderService;
import com.bookstore.service.UserHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;
    
    @Autowired
    private UserHistoryService userHistoryService;

    @Autowired
    private CartService cartService;

    @PostMapping
    public ResponseEntity<?> createOrder(@RequestBody OrderDTO orderDTO) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = ((User) auth.getPrincipal()).getId();
        orderDTO.setUserId(userId);
        orderDTO.setExpireTime(LocalDateTime.now().plusHours(1));
        OrderDTO createdOrder = orderService.createOrder(orderDTO);

        // 记录订单中的每本书的购买历史
        if (createdOrder != null && createdOrder.getItems() != null) {

            try {
                createdOrder.getItems().forEach(item -> {
                    try {
                        userHistoryService.addHistory(userId, item.getBook().getId(), "ORDER");
                    } catch (Exception e) {
                        log.error("记录订单历史失败: " + e.getMessage(), e);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResponseEntity.ok(createdOrder);
    }

    @GetMapping
    public ResponseEntity<?> getUserOrders() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = ((User) auth.getPrincipal()).getId();
        return orderService.getUserOrders(userId);
    }

    @DeleteMapping("/{orderId}")
    public ResponseEntity<?> deleteOrder(@PathVariable Long orderId){
        return orderService.deleteById(orderId);
    }

    @GetMapping("/{orderId}")
    public ResponseEntity<?> getOrderById(@PathVariable Long orderId) {
        return orderService.getOrderById(orderId);
    }

    @PutMapping("/{orderId}/status")
    public ResponseEntity<?> updateOrderStatus(
            @PathVariable Long orderId,
            @RequestBody Map<String, String> statusMap) {
        String status = statusMap.get("status");
        return orderService.updateOrderStatus(orderId, status);
    }

     /**
      * 支付订单
      */
     @PostMapping("/{orderId}/pay")
     public ResponseEntity<?> payOrder(
             @PathVariable Long orderId,
             @RequestBody Map<String, String> paymentInfo) {
         String paymentMethod = paymentInfo.get("paymentMethod");
         return orderService.payOrder(orderId, paymentMethod);
     }
    
    // /**
    //  * 获取订单物流信息
    //  */
    // @GetMapping("/{orderId}/logistics")
    // public ResponseEntity<?> getOrderLogistics(@PathVariable Long orderId) {
    //     return orderService.getOrderLogistics(orderId);
    // }
    
}